// ============================== 导入依赖 ============================== //

import IS from './is'
import axios from 'axios'

const BODY_CLASS = `CoreBody CoreBody-${IS.isApp() ? 'app' : ''}${IS.isWeb() ? 'web' : ''}`
document.body.className = `${BODY_CLASS} default`

// ============================== 导出主题工具 ============================== //

export default {
  /**
   * 主题初始化
   */
  themeInit() {
    const theme = localStorage.THEME || 'default'
    this.themeChange(theme)
  },

  /**
   * 主题切换
   */
  themeChange(theme) {
    const matched = this.THEME.DICT.find((item) => item[0] === theme)

    // 不存在
    if (!matched) return resetTheme('主题', this)

    const folder = theme === 'default' ? 'css' : `css-${theme}`

    // 是否已加载 link
    if (matched[2]) setTheme(theme)
    else {
      matched[2] = true
      const link = document.createElement('link')
      link.id = `theme-${theme}.css`
      link.rel = 'stylesheet'
      link.href = this.asset(`${folder}/theme/index.css`)
      link.onload = () => setTheme(theme)
      link.onerror = () => resetTheme(matched[1], this)
      document.head.appendChild(link)
    }

    // 是否已替换 style
    if (!matched[3]) {
      matched[3] = true
      const url = this.asset(`${folder}/config.json`)
      axios.get(url).then(({ data }) => setStyle(data, this)).catch(() => ({}))
    }
  },
}

// ============================== 内部方法 ============================== //

const setTheme = (theme) => {
  localStorage.THEME = theme
  document.body.className = `${BODY_CLASS} ${theme}`
}

const resetTheme = (name, CORE) => {
  CORE.MSG.error(`${name}加载失败`)
  CORE.THEME.current = localStorage.THEME || 'default'
  document.body.className = `${BODY_CLASS} ${CORE.THEME.current}`
}

const setStyle = (data, CORE) => {
  let str = CORE.THEME.STYLE

  // 主题
  const theme = `.${CORE.THEME.current}`
  str = str.replace(/\n/g, '').replace(/\$theme/g, theme)

  // 主要颜色
  const primary = data.global['$--color-primary'] || '#409EFF'
  str = str.replace(/rgba\(\$Primary/g, toRGBA(primary)).replace(/\$Primary/g, primary)

  // 成功颜色
  const success = data.global['$--color-success'] || '#67C23A'
  str = str.replace(/rgba\(\$Success/g, toRGBA(success)).replace(/\$Success/g, success)

  // 警告颜色
  const warning = data.global['$--color-warning'] || '#E6A23C'
  str = str.replace(/rgba\(\$Warning/g, toRGBA(warning)).replace(/\$Warning/g, warning)

  // 危险颜色
  const danger = data.global['$--color-danger'] || '#F56C6C'
  str = str.replace(/rgba\(\$Danger/g, toRGBA(danger)).replace(/\$Danger/g, danger)

  // 信息颜色
  const info = data.global['$--color-info'] || '#909399'
  str = str.replace(/rgba\(\$Info/g, toRGBA(info)).replace(/\$Info/g, info)

  // 纯黑颜色
  const black = data.global['$--color-black'] || '#000000'
  str = str.replace(/rgba\(\$Black/g, toRGBA(black)).replace(/\$Black/g, black)

  // 纯白颜色
  const white = data.global['$--color-white'] || '#FFFFFF'
  str = str.replace(/rgba\(\$White/g, toRGBA(white)).replace(/\$White/g, white)

  // 主要文本
  const primaryText = data.global['$--color-text-primary'] || '#303133'
  str = str.replace(/\$PrimaryText/g, primaryText)

  // 常规文本
  const regularText = data.global['$--color-text-regular'] || '#606266'
  str = str.replace(/\$RegularText/g, regularText)

  // 次要文本
  const secondaryText = data.global['$--color-text-secondary'] || '#909399'
  str = str.replace(/\$SecondaryText/g, secondaryText)

  // 提示文本
  const placeholder = data.global['$--color-text-placeholder'] || '#C0C4CC'
  str = str.replace(/\$Placeholder/g, placeholder)

  // 基本边框
  const borderBase = data.global['$--border-color-base'] || '#DCDFE6'
  str = str.replace(/\$BorderBase/g, borderBase)

  // 更亮边框
  const borderLighter = data.global['$--border-color-lighter'] || '#EBEEF5'
  str = str.replace(/\$BorderLighter/g, borderLighter)

  // 较亮边框
  const borderLight = data.global['$--border-color-light'] || '#E4E7ED'
  str = str.replace(/\$BorderLight/g, borderLight)

  // 超亮边框
  const borderExtralight = data.global['$--border-color-extra-light'] || '#F2F6FC'
  str = str.replace(/\$BorderExtralight/g, borderExtralight)

  const style = document.createElement('style')
  style.innerText = str
  document.head.appendChild(style)
}

const toRGBA = (color) => {
  const r = parseInt(color.slice(1, 3), 16)
  const g = parseInt(color.slice(3, 5), 16)
  const b = parseInt(color.slice(5, 7), 16)
  return `rgba(${r}, ${g}, ${b}`
}
